package com.jtpay.sdk.util;

import android.annotation.SuppressLint;
import android.os.Environment;

import com.jtpay.sdk.BuildConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by tshsbapple on 16/12/5.
 * 数据库文件处理
 */
public class DbUtils {
    private static String ApkPath = "/data/data/" + BuildConfig.APPLICATION_ID + "/databases/";
    @SuppressLint("SdCardPath")
    public static final String SDPATHHome = Environment.getExternalStorageDirectory()
            + "/" + BuildConfig.AppName;
    public static String SDPath = SDPATHHome + "/db/";
    public static String DbName = BuildConfig.dbName;
    @SuppressLint("SimpleDateFormat")
    private static SimpleDateFormat logfile = new SimpleDateFormat(
            "yyyyMMdd-HHmmss");// 日志文件格式

    /**
     * 拷贝sd卡数据库文件到
     */
    public static void copyRawDBToApkDb()
            throws IOException {
        if (isFileExist(ApkPath, DbName)) {
            InputStream is = new FileInputStream(ApkPath + DbName);
            String needWriteFiel = logfile.format(new Date());
            int length;
            byte[] buffer = new byte[1024];
            OutputStream fos = new FileOutputStream(SDPath + DbName + needWriteFiel);
            while ((length = is.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
            fos.flush();
            fos.close();
            is.close();
        }
        JftLogUtil.log("数据库导出完成");

//        if (isFileExist(SDPath, DbName)) {
//            delFile(ApkPath, DbName);
//            InputStream is = new FileInputStream(SDPath + DbName);
//
//            int length;
//            byte[] buffer = new byte[1024];
//
//            OutputStream fos = new FileOutputStream(ApkPath + DbName);
//
//            while ((length = is.read(buffer)) != -1) {
//                fos.write(buffer, 0, length);
//            }
//            fos.flush();
//            fos.close();
//            is.close();
//
//        }
//
//        delFile(SDPath, DbName);

    }

    //创建sd上文件夹
    public static boolean createDir(String path) {
        File dirFile = new File(path);
        if (dirFile.exists()) {
            JftLogUtil.log("createDir:" + path + "exist");
            return true;
        } else {
            JftLogUtil.log("createDir:" + path);
            return dirFile.mkdir();
        }
    }

    public static boolean isFileExist(String path, String fName) {
        File f = new File(path + fName);
        f.isFile();
        return f.exists();
    }

    public static void delFile(String path, String fileName) {
        File file = new File(path, fileName);
        if (file.isFile()) {
            file.delete();
        }
    }
}
